package com.smallkingson.ylib.core.utils;

import android.app.Activity;
import android.view.View;

import com.smallkingson.ylib.core.Yr;
import com.smallkingson.ylib.core.annotations.FindView;
import com.smallkingson.ylib.core.annotations.OnClick;
import com.smallkingson.ylib.view.utils.YViews;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2015/12/16.
 */
public class YInjections {
    public static void inject(Activity activity) {
        inject(activity, activity.getWindow().getDecorView());
    }
    public static void inject(Object o, View v) {

        injectField(o, v);
        injectMethod(o, v);
    }

    private static void injectMethod(final Object o, View v) {
        Method[] declaredMethods = o.getClass().getDeclaredMethods();
        for (final Method method : declaredMethods) {
            method.setAccessible(true);
            OnClick annotation = method.getAnnotation(OnClick.class);
            if (annotation != null) {
                final View view = v.findViewById(annotation.id());

                if(view==null){
                    Yr.logError(new Exception("view==null  id = "+annotation.id()));
                    continue;
                }
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            method.invoke(o, view);
                        } catch (Exception e) {
                            Yr.logError(v.getId()+"",e);
                        }
                    }
                });
            }
        }
    }

    /*
     * field
     */
    private static void injectField(Object o, View v) {

        Field[] Fields = o.getClass().getDeclaredFields();

        for (Field field : Fields) {

            field.setAccessible(true);

            FindView findView = field.getAnnotation(FindView.class);

            if (findView != null) {
                try {
                    field.set(o, v.findViewById(findView.id()));
                } catch (IllegalAccessException e) {
                    Yr.logError(field.toString(),e);
                } catch (IllegalArgumentException e) {
                    Yr.logError(field.toString(),e);
                }
            }
        }
    }


}
